package com.xtianzhuang.www.service.impl;

import java.lang.reflect.Method;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.xtianzhuang.www.service.CommonService;
import com.xtianzhuang.www.service.base.BaseServiceBiz;
import com.xtianzhuang.www.utils.PageData;
import com.xtianzhuang.www.utils.SpringContextHolder;
import com.xtianzhuang.www.utils.StringUtil;

@Service("commonServiceBiz")
@Transactional(rollbackFor = Exception.class)
public class CommonServiceBiz extends BaseServiceBiz implements CommonService {
	private static final String SELECT_LIST = "selectByExample";
	private static final String SELECT_COUNT = "countByExample";
	@Override
	public PageData getPageData(Object example) {
		// TODO Auto-generated method stub
		PageData data = new PageData<>();
		try {
			String exampleName = example.getClass().getName();
			String dtoName = exampleName.substring(exampleName.lastIndexOf(".") + 1)
					.replace("Example", "");
			String mapperName = "";
			// 自动注入的 V开头的视图不知道为啥是小写，待思考
			if (dtoName.startsWith("V")) {
				mapperName = dtoName + "Mapper";
			} else {
				mapperName = StringUtil.toLowerCaseFirstOne(dtoName) + "Mapper";
			}

			Object mapper = SpringContextHolder.getBean(mapperName);
			Object[] params = new Object[1];
			params[0] = example;
			Class[] types = new Class[1];
			types[0] = example.getClass();
			List<Object> list = (List) this.callBean(mapper, SELECT_LIST, params, types);
			long total = (Long) this.callBean(mapper, SELECT_COUNT, params, types);
			data.setData(list);
			data.setTotal(total);
			logger.error(JSON.toJSONString(data));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data;
	}

	public Object callBean(Object instance, String method_name, Object[] params, Class[] types) throws Exception {
		if (params != null && types != null) {
			for (int i = 0; i < types.length; ++i) {
				if (types[i] == null) {
					types[i] = params[i].getClass();
				}
			}
		}

		Method method = instance.getClass().getMethod(method_name, types);
		return method.invoke(instance, params);
	}

}
